package com.feib.stms.dao;

import java.io.IOException;


import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.feib.stms.model.MailQueue;
import com.feib.stms.service.MailJobService;

import com.feib.stms.util.MailContentTemplate;



@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"applicationContext-config.xml", "applicationContext-dao.xml"})
public class MailTester {
	
	
	
	@Autowired
	@Qualifier("mailJobService")
	private MailJobService mailJob;

	@Resource(name="mailQueueDao")
	public   MailQueueDao mailQueueDao;
	
	@Resource(name="htmlMailFolder")
	private String htmlMailFolder;
	
	@Resource(name="defaultMailFrom")
    private String defaultMailFrom;

    @Resource(name="defaultMailReturnReceiptTo")
    private String defaultMailReturnReceiptTo;
	
    @Resource(name="txManager")
    private PlatformTransactionManager transactionManager;
	
	@Test
	public void test() throws IOException
	{

        StringBuffer mailTo = new StringBuffer();
 
        String messageTile = "TEST";
        StringBuffer paragraph1 = new StringBuffer();
        
        String[] paragraphs = new String[]{"您好", paragraph1.toString(), "謝謝"};

        MailContentTemplate mailContentTemplate = new MailContentTemplate(messageTile, paragraphs, htmlMailFolder);
        MailQueue mailQueue = mailContentTemplate.createMailQueue();
        mailQueue.setMailTo("latte1855@gmail.com");
        mailQueue.setMailFrom(defaultMailFrom);
        mailQueue.setMailReturnReceiptTo(defaultMailReturnReceiptTo);

        // 建立交易的定義，每一次都是新的 Transaction
        DefaultTransactionDefinition definition = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        
		TransactionStatus status = transactionManager.getTransaction(definition);
        try {
            mailQueueDao.insert(mailQueue);
        }
        catch (Exception e2) {
            transactionManager.rollback(status);
            status = null; // roll back 不需要再呼叫 commit
            try {
				throw e2;
			} catch (Exception e) {
				// TODO 自動產生 catch 區塊
				e.printStackTrace();
			}
        }
        if (null != status)
            transactionManager.commit(status);

        
        mailJob.execute(mailQueue.getMailQueuePk());
        mailQueue = null; // free resource
	}

}
